const childProcess = require('child_process')
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleWare = require('webpack-dev-middleware');
const fs = require('fs');
const http = require('http');
const https = require('https');
const privateKey = fs.readFileSync('./ssl/localServer.key', 'utf-8');
const certificate = fs.readFileSync('./ssl/localServer.crt', 'utf-8');
const credentials = { key: privateKey, cert: certificate };

const app = express();
const config = require('./webpack.dev');
const compiler = webpack(config);

app.use(webpackDevMiddleWare(compiler));
app.use(express.static('./'));

const httpPort = 3000;
const httpServer = http.createServer(app);
httpServer.listen(httpPort, () => {
    console.log('http server is running on: http://localhost:' + httpPort);
});

const httpsPort = 3001;
const httpsServer = https.createServer(credentials, app);
httpsServer.listen(httpsPort, () => {
    console.log('https server is running on: https://localhost:' + httpsPort);
});

const url = 'https://localhost:' + httpsPort + '/index.html';
childProcess.exec('start msedge ' + url, (err, stdout, stderr) => {
    if (err) {
        childProcess.exec('start chrome ' + url, (err, stdout, stderr) => {
            if (err) {
                childProcess.exec('start firefox ' + url, (err, stdout, stderr) => {
                    if (err) {
                        console.log('No suitable browser found (recommended:edge,chrome,firefox)!');
                    }
                });
            }
        });
    }
});